package com.ruoyi.system.service.impl;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson2.JSONArray;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.form.UserTaskAddData;
import com.ruoyi.system.mapper.*;

import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang3.StringUtils;
import com.ruoyi.system.domain.form.BuzTaskAddData;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.ruoyi.system.service.IBuzMemberService;
import com.ruoyi.system.service.IBuzTaskService;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import static java.lang.Math.random;

/**
 * 活动信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-08-27
 */
@Service
public class BuzTaskServiceImpl implements IBuzTaskService 
{
	
	private static final Logger log = LoggerFactory.getLogger(BuzTaskServiceImpl.class);
	
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private BuzTaskMapper buzTaskMapper;
    @Autowired
    private BuzTaskQuestionMapper buzTaskQuestionMapper;
    @Autowired
    private BuzTaskOptionMapper buzTaskOptionMapper;
    @Autowired
    private BuzTaskAwardsMapper buzTaskAwardsMapper;
    @Autowired
    private BuzTaskAreaMapper buzTaskAreaMapper;
    @Autowired
    private BuzTaskUserMapper buzTaskUserMapper;
    @Autowired
    private BuzTaskUserQuestionMapper buzTaskUserQuestionMapper;
    @Autowired
    private BuzTaskUserOptionMapper buzTaskUserOptionMapper;

    @Autowired
    private BuzMemberMapper buzMemberMapper;
    @Autowired
    private IBuzMemberService buzMemberService;

    @Autowired
    private BuzTaskAwardsJackpotMapper buzTaskAwardsJackpotMapper;
    /**
     * 查询活动信息
     * 
     * @param id 活动信息主键
     * @return 活动信息
     */
    @Override
    public BuzTask selectBuzTaskById(String id)
    {
        return buzTaskMapper.selectBuzTaskById(id);
    }

    /**
     * 查询活动信息列表
     * 
     * @param buzTask 活动信息
     * @return 活动信息
     */
    @Override
    public List<BuzTask> selectBuzTaskList(BuzTask buzTask)
    {
        return buzTaskMapper.selectBuzTaskList(buzTask);
    }

    /**
     * 新增活动信息
     * 
     * @param buzTask 活动信息
     * @return 结果
     */
    @Override
    public int insertBuzTask(BuzTask buzTask)
    {
        buzTask.setStatus("0");
        return buzTaskMapper.insertBuzTask(buzTask);
    }

    /**
     * 修改活动信息
     * 
     * @param buzTask 活动信息
     * @return 结果
     */
    @Override
    public int updateBuzTask(BuzTask buzTask)
    {
        return buzTaskMapper.updateBuzTask(buzTask);
    }

    /**
     * 批量删除活动信息
     * 
     * @param ids 需要删除的活动信息主键
     * @return 结果
     */
    @Override
    public int deleteBuzTaskByIds(String[] ids)
    {
        return buzTaskMapper.deleteBuzTaskByIds(ids);
    }

    /**
     * 删除活动信息信息
     * 
     * @param id 活动信息主键
     * @return 结果
     */
    @Override
    public int deleteBuzTaskById(String id)
    {
        return buzTaskMapper.deleteBuzTaskById(id);
    }

    /**
     * 根据活动状态获取活动列表
     *
     * @param status 活动状态
     * @return 结果
     */
    @Override
    public List<BuzTask> getBuzTaskListByStatus(String status)
    {
        return buzTaskMapper.getBuzTaskListByStatus(status);
    }

    /**
     * 保存或更新活动设置
     *
     */
    @Transactional
    public BuzTaskAddData saveBuzTask(BuzTaskAddData addData)
    {
        BuzTask buzTask = addData.getBuzTask();
        if(StringUtils.isBlank(buzTask.getId())) {
            buzTask.setStatus("0");
        }
        if(addData.getAppSetting()!=null) {
        	buzTask.setAppSetting(addData.getAppSetting().toJSONString());
        }
        String taskId = saveOrUpdateBuzTask(buzTask);
        
        //删除原有题库，新增本次题库        
        buzTaskQuestionMapper.deleteBuzTaskQuestionByTaskId(taskId);
        buzTaskOptionMapper.deleteBuzTaskOptionByTaskId(taskId);
        if(addData.getBuzTaskQuestions() != null && !addData.getBuzTaskQuestions().isEmpty()) {
            for (BuzTaskQuestion buzTaskQuestion : addData.getBuzTaskQuestions()) {
                buzTaskQuestion.setBuzTaskId(taskId);
                String taskQuestionId = saveOrUpdateBuzTaskQuestion(buzTaskQuestion);
                if (buzTaskQuestion.getBuzTaskOptions() != null && !buzTaskQuestion.getBuzTaskOptions().isEmpty()) {
                	//删除已有可选项，插入新的可选项
                	//buzTaskOptionMapper.deleteBuzTaskOptionByQuestionId(taskQuestionId);
                    for (BuzTaskOption buzTaskOption : buzTaskQuestion.getBuzTaskOptions()) {
                    	//buzTaskOption.setId(null);
                        buzTaskOption.setBuzTaskId(taskId);
                        buzTaskOption.setBuzTaskQuestionId(taskQuestionId);
                        saveOrUpdateBuzTaskOption(buzTaskOption);
                    }
                }
            }
        }

        for (BuzTaskAwards buzTaskAwards : addData.getBuzTaskAwards()) {
            buzTaskAwards.setBuzTaskId(taskId);
            saveOrUpdateBuzTaskAwards(buzTaskAwards);
        }
        for (BuzTaskArea buzTaskArea : addData.getBuzTaskArea()){
            buzTaskArea.setBuzTaskId(taskId);
            saveOrUpdateBuzTaskArea(buzTaskArea);
        }

        List<BuzTaskAwards> buzTaskAwardsList = buzTaskAwardsMapper.selectBuzTaskAwardsListByTaskId(taskId);
        for (BuzTaskAwards buzTaskAwards : buzTaskAwardsList) {
            int jackpotNum = buzTaskAwards.getAwardNums();
            //奖项数量被修改时，修改奖池数量
            //已经中奖的数量
            int awardsNum = buzTaskAwardsJackpotMapper.countAllByTaskAwardsId(buzTaskAwards.getId());
            if(awardsNum != 0){
                //新的总量-已抽奖的数量 = 奖池剩余数量
                jackpotNum = buzTaskAwards.getAwardNums() - awardsNum;
            }
            if(jackpotNum > 0) {
                //删除剩余未中奖的奖池，并重新生成
                buzTaskAwardsJackpotMapper.deleteByTaskAwardsId(buzTaskAwards.getId());
                List<BuzTaskAwardsJackpot> buzTaskAwardsJackpots = new ArrayList();
                for (int i = 0; i < jackpotNum; i++) {
                    BuzTaskAwardsJackpot buzTaskAwardsJackpot = new BuzTaskAwardsJackpot();
                    buzTaskAwardsJackpot.setId(generateGuid());
                    buzTaskAwardsJackpot.setBuzTaskId(taskId);
                    buzTaskAwardsJackpot.setBuzTaskAwardsId(buzTaskAwards.getId());
                    buzTaskAwardsJackpot.setAwardName(buzTaskAwards.getAwardName());
                    buzTaskAwardsJackpot.setAwardsLevel(buzTaskAwards.getAwardsLevel());
//                    buzTaskAwardsJackpotMapper.insertBuzTaskAwardsJackpot(buzTaskAwardsJackpot);
                    buzTaskAwardsJackpots.add(buzTaskAwardsJackpot);
                }
                buzTaskAwardsJackpotMapper.batchInsertBuzTaskAwardsJackpot(buzTaskAwardsJackpots);

            }else{
                //throw new Exception("已中奖的数量不能大于修改后的奖项数量");
            }                        
        }
        
      //更新剩余奖品数量
        List<BuzTaskAwardsJackpot> jackpotList=buzTaskAwardsJackpotMapper.selectBuzTaskAwardsNums(taskId);
        for(int i=0;i<jackpotList.size();i++) {
        	BuzTaskAwardsJackpot jackpot=jackpotList.get(i);
        	BuzTaskAwards buzTaskAwards=new BuzTaskAwards();
        	buzTaskAwards.setAwardsLevel(jackpot.getAwardsLevel());
        	buzTaskAwards.setBuzTaskId(taskId);
        	buzTaskAwards.setLeftAwardNums(jackpot.getAwards());
        	buzTaskAwardsMapper.updateBuzTaskAwardsLeft(buzTaskAwards);
        }
        
        return getAllByTaskId(taskId);
    }
    /**
     *
     * 保存用户答题内容
     * */
    @Transactional
    public BuzTaskUser saveUserTaskOption(BuzTaskAddData addData){

        BuzTaskUser user = addData.getBuzTaskUser();
        List<BuzTaskUserQuestion> buzTaskUserQuestions = addData.getBuzTaskUserQuestions();
        List<BuzTaskUserOption> buzTaskUserOptions = new ArrayList<>();
        
        BuzTaskQuestion questionParam = new BuzTaskQuestion();
        questionParam.setBuzTaskId(user.getTaskId());
        
        log.info("----------user.getTaskId()----------"+user.getTaskId());
        System.out.println("----------user.getTaskId()----------"+user.getTaskId());
        
        List<BuzTaskQuestion> buzTaskQuestions = buzTaskQuestionMapper.selectBuzTaskQuestionList2(questionParam);
        /*
        for (BuzTaskQuestion question : buzTaskQuestions) {
            BuzTaskOption optionParam = new BuzTaskOption();
            optionParam.setBuzTaskQuestionId(question.getId());
            optionParam.setBuzTaskId(user.getTaskId());
            question.setBuzTaskOptions(buzTaskOptionMapper.selectBuzTaskOptionList(optionParam));//一个一个循环查询啊
        }
        */

        for(BuzTaskUserQuestion userQuestion : buzTaskUserQuestions) {
            userQuestion.setBuzTaskUserId(user.getId());
            userQuestion.setId(generateGuid());
            //比较题库里的答案与用户提交的答案，得出用户考试结果
            for(int i=0;i<buzTaskQuestions.size();i++) {
            	BuzTaskQuestion question=buzTaskQuestions.get(i);
            	if(userQuestion.getAsk().equals(question.getAsk())) {
            		
            		log.info("----------question.getAnswerKey()----------"+question.getAnswerKey());
                    System.out.println("----------question.getAnswerKey()----------"+question.getAnswerKey());
                    
                    log.info("----------userQuestion.getUserAnswer()----------"+userQuestion.getUserAnswer());
                    System.out.println("----------userQuestion.getUserAnswer()----------"+userQuestion.getUserAnswer());
            		
            		List<String> answerKey = Arrays.stream(question.getAnswerKey().split(",")).sorted().collect(Collectors.toList());
                    List<String> userAnswer = Arrays.stream(userQuestion.getUserAnswer().split(",")).sorted().collect(Collectors.toList());
                    if(answerKey.equals(userAnswer)){
                        userQuestion.setRightWrong(1);
                    }else{
                        userQuestion.setRightWrong(0);
                    }
            	}
            }
            
            
            buzTaskUserQuestionMapper.insertBuzTaskUserQuestion(userQuestion);

            for(BuzTaskUserOption buzTaskUserOption : userQuestion.getBuzTaskUserOptions()){
                buzTaskUserOption.setBuzTaskId(userQuestion.getBuzTaskId());
                buzTaskUserOption.setBuzTaskUserQuestionId(userQuestion.getId());
                buzTaskUserOption.setBuzTaskUserId(user.getId());
                if(buzTaskUserOption.getId()==null) {
                	buzTaskUserOption.setId(UUID.randomUUID().toString().replace("-", ""));
                }
                //TODO
                
//                buzTaskUserOptionMapper.insertBuzTaskUserOption(buzTaskUserOption);
                
                buzTaskUserOptions.add(buzTaskUserOption);
            }
            
        }
        //改成批量保存
        //buzTaskUserQuestionMapper.batchInsertBuzTaskUserQuestion(buzTaskUserQuestions);
        buzTaskUserOptionMapper.batchInsertBuzTaskUserOption(buzTaskUserOptions);

        //通过taskId获取活动配置
        BuzTask task = buzTaskMapper.selectBuzTaskById(addData.getBuzTask().getId());
        //计算答题总分
        int totalPoint = (int) buzTaskUserQuestions.stream().filter(f->f.getRightWrong().equals(1)).count() * task.getQuestionPoints();
        user.setTotalPoint(totalPoint);
        //如果总分大于等于抽奖活动分数要求
        if(totalPoint >= task.getAwardsPoints()){
            user.setCanAwardsFlag(1);
        }else{
            user.setCanAwardsFlag(0);
        }
        // 查询是否存在，不存在则新增，存在则修改
        BuzTaskUser taskUser =  buzTaskUserMapper.selectBuzTaskUserById(user.getId());
        
        
        
        if(taskUser!=null) {
        	buzTaskUserMapper.updateBuzTaskUser(user);
        }else {
        	buzTaskUserMapper.insertBuzTaskUser(user);
        }
        
        //保证AwardsTime和ReceiveAwardsTime为空
        buzTaskUserMapper.updateSaveQuestion(user);
        
        
        int todayRemainTimes = task.getEveryoneEverydateAwardsTimes() - buzTaskUserMapper.getAwardCountByTaskIdAndMemberIdPerDay(taskUser);
        int remainTimes = task.getTotalAwardsTimes() - buzTaskUserMapper.getAwardTimesByTaskIdAndMemberId(taskUser);
        user.setTodayRemainTimes(todayRemainTimes);
        user.setRemainTimes(remainTimes);
        return user;
    }
    
    
    /**
    *
    * 保存用户练习内容
    * */
   public BuzTaskUser saveUserPraticTask(BuzTaskAddData addData){

       BuzTaskUser user = addData.getBuzTaskUser();
       List<BuzTaskUserQuestion> buzTaskUserQuestions = addData.getBuzTaskUserQuestions();
       List<BuzTaskUserOption> buzTaskUserOptions = new ArrayList<>();

       for(BuzTaskUserQuestion userQuestion : buzTaskUserQuestions) {
           userQuestion.setBuzTaskUserId(user.getId());
           userQuestion.setId(generateGuid());
           List<String> answerKey = Arrays.stream(userQuestion.getAnswerKey().split(",")).sorted().collect(Collectors.toList());
           List<String> userAnswer = Arrays.stream(userQuestion.getUserAnswer().split(",")).sorted().collect(Collectors.toList());
           if(answerKey.equals(userAnswer)){
               userQuestion.setRightWrong(1);
           }else{
               userQuestion.setRightWrong(0);
           }
//           buzTaskUserQuestionMapper.insertBuzTaskUserQuestion(userQuestion);

           for(BuzTaskUserOption buzTaskUserOption : userQuestion.getBuzTaskUserOptions()){
               buzTaskUserOption.setBuzTaskId(userQuestion.getBuzTaskId());
               buzTaskUserOption.setBuzTaskUserQuestionId(userQuestion.getId());
               buzTaskUserOption.setBuzTaskUserId(user.getId());
               //TODO
               /*fly 临时处理沒有id的情況*/
               if(buzTaskUserOption.getId()==null) {
               	buzTaskUserOption.setId(UUID.randomUUID().toString().replace("-", ""));
               }
//               buzTaskUserOptionMapper.insertBuzTaskUserOption(buzTaskUserOption);
           }
           buzTaskUserOptions.addAll(userQuestion.getBuzTaskUserOptions());
       }
       //改成批量保存
       //buzTaskUserQuestionMapper.batchInsertBuzTaskUserQuestion(buzTaskUserQuestions);
       //buzTaskUserOptionMapper.batchInsertBuzTaskUserOption(buzTaskUserOptions);

       //通过taskId获取活动配置
       BuzTask task = buzTaskMapper.selectBuzTaskById(addData.getBuzTask().getId());
       //计算答题总分
       int totalPoint = (int) buzTaskUserQuestions.stream().filter(f->f.getRightWrong().equals(1)).count() * task.getQuestionPoints();
       user.setTotalPoint(totalPoint);
       //如果总分大于等于抽奖活动分数要求
       if(totalPoint >= task.getAwardsPoints()){
           user.setCanAwardsFlag(1);
       }else{
           user.setCanAwardsFlag(0);
       }
       // 查询是否存在，不存在则新增，存在则修改
       BuzTaskUser taskUser =  buzTaskUserMapper.selectBuzTaskUserById(user.getId());
       
       
       
       if(taskUser!=null) {
       	//buzTaskUserMapper.updateBuzTaskUser(user);
       }else {
       	//buzTaskUserMapper.insertBuzTaskUser(user);
       }
       
       //保证AwardsTime和ReceiveAwardsTime为空
       //buzTaskUserMapper.updateSaveQuestion(user);
       
       
       int todayRemainTimes = task.getEveryoneEverydateAwardsTimes() - buzTaskUserMapper.getAwardCountByTaskIdAndMemberIdPerDay(taskUser);
       int remainTimes = task.getTotalAwardsTimes() - buzTaskUserMapper.getAwardTimesByTaskIdAndMemberId(taskUser);
       user.setTodayRemainTimes(todayRemainTimes);
       user.setRemainTimes(remainTimes);
       return user;
   }
    
    /**
     * 根据活动id获取活动设置
     *
     */
    @Transactional
    public BuzTaskAddData getAllByTaskId(String taskId){
        BuzTaskAddData addData = new BuzTaskAddData();
        BuzTask buzTask = buzTaskMapper.selectBuzTaskById(taskId);

        BuzTaskQuestion questionParam = new BuzTaskQuestion();
        questionParam.setBuzTaskId(buzTask.getId());
        List<BuzTaskQuestion> buzTaskQuestions = buzTaskQuestionMapper.selectBuzTaskQuestionList2(questionParam);
        for(BuzTaskQuestion question : buzTaskQuestions) {
            BuzTaskOption optionParam = new BuzTaskOption();
            optionParam.setBuzTaskQuestionId(question.getId());
            optionParam.setBuzTaskId(buzTask.getId());
            question.setBuzTaskOptions(buzTaskOptionMapper.selectBuzTaskOptionList(optionParam));
        }
        BuzTaskAwards awardsParam = new BuzTaskAwards();
        awardsParam.setBuzTaskId(buzTask.getId());
        List<BuzTaskAwards> buzTaskAwards = buzTaskAwardsMapper.selectBuzTaskAwardsList(awardsParam);

        addData.setBuzTask(buzTask);
        if(buzTask.getAppSetting()!=null) {
        	addData.setAppSetting(JSONObject.parseObject(buzTask.getAppSetting()));
        }
        addData.setBuzTaskQuestions(buzTaskQuestions);
        addData.setBuzTaskAwards(buzTaskAwards);

        return addData;
    }
    @Transactional
    public BuzTaskSimple getBuzTaskSimple(String taskId){
        BuzTask buzTask = buzTaskMapper.selectBuzTaskById(taskId);
        // 补充奖项数据
        BuzTaskAwards buzTaskAwards = new BuzTaskAwards();
        buzTaskAwards.setBuzTaskId(taskId);
        List<BuzTaskAwards> buzTaskAwardses = buzTaskAwardsMapper.selectBuzTaskAwardsList(buzTaskAwards);


        List<BuzTaskAwardsSimple> taskAwards = buzTaskAwardses.stream().map(e->{
        	BuzTaskAwardsSimple model =  new BuzTaskAwardsSimple();
        	model.setId(e.getId());
        	model.setAwardsLevel(e.getAwardsLevel());
        	model.setAwardNums(e.getAwardNums());
        	model.setAwardName(e.getAwardName());
        	return model;
        }).collect(Collectors.toList());

        BuzTaskSimple buzTaskSimple = new BuzTaskSimple();
        buzTaskSimple.setId(buzTask.getId());
        buzTaskSimple.setTitle(buzTask.getTitle());
        buzTaskSimple.setStartTime(buzTask.getStartTime());
        buzTaskSimple.setEndTime(buzTask.getEndTime());
        buzTaskSimple.setStatus(buzTask.getStatus());
        buzTaskSimple.setMemo(buzTask.getMemo());
        buzTaskSimple.setOrganizer(buzTask.getOrganizer());
        buzTaskSimple.setOrganizerWebsite(buzTask.getOrganizerWebsite());
        buzTaskSimple.setAwards(taskAwards);
        buzTaskSimple.setAwardsPoints(buzTask.getAwardsPoints());
        
        buzTaskSimple.setContactInfo(buzTask.getContactInfo());
        buzTaskSimple.setContactInfoInput(buzTask.getContactInfoInput());
        
        return buzTaskSimple;
    }

    /**
     * 将对象转成json存入redis
     * @param listName
     * @param object
     */
    public void saveObjectToList(String listName, List<BuzTaskQuestion> questions){
        try {
            redisTemplate.opsForValue().set(listName, questions);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 将json按类型转型从redis取出
     * @param listName
     * @param objectClass
     * @return
     * @param <T>
     */
    public <T> List<T> getObjectList(String listName, Class<T> objectClass){
        try{
            JSONArray jsonArray = (JSONArray) redisTemplate.opsForValue().get(listName);
            return jsonArray.toJavaList(objectClass);
        } catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 用户根据活动id获取活动问题
     *
     */
    @Transactional
    public BuzTaskAddData userGetTaskByTaskId(String taskId, String memberId,String longitude,String latitude) {

        BuzTaskAddData addData = new BuzTaskAddData();
        BuzTask buzTask = buzTaskMapper.selectBuzTaskById(taskId);
        BuzTaskQuestion questionParam = new BuzTaskQuestion();
        questionParam.setBuzTaskId(buzTask.getId());
        
        BuzMember member=buzMemberService.selectBuzMemberById(memberId);
        addData.setMember(member);

        BuzTaskUser taskUser = new BuzTaskUser();
        taskUser.setTaskId(taskId);
        taskUser.setMemberId(memberId);
        taskUser.setStartTime(DateUtils.getNowDate());
        taskUser.setEndTime(DateUtils.addSeconds(taskUser.getStartTime(), buzTask.getLimitTimes()));
        taskUser.setLongitude(longitude);
        taskUser.setLatitude(latitude);
        //保存答题活动
        String taskUserId = saveOrUpdateBuzTaskUser(taskUser);
        
        taskUser.setId(taskUserId);
        List<BuzTaskQuestion> buzTaskQuestions;
        //如果redis存在题库，则从redis取，否则从数据库取出，存入redis
        /*
        if(Boolean.TRUE.equals(redisTemplate.hasKey(taskId))) {
            buzTaskQuestions = getObjectList(taskId, BuzTaskQuestion.class);
        }else {
            buzTaskQuestions = buzTaskQuestionMapper.selectBuzTaskQuestionList(questionParam);
            for (BuzTaskQuestion question : buzTaskQuestions) {
                BuzTaskOption optionParam = new BuzTaskOption();
                optionParam.setBuzTaskQuestionId(question.getId());
                optionParam.setBuzTaskId(buzTask.getId());
                question.setBuzTaskOptions(buzTaskOptionMapper.selectBuzTaskOptionList(optionParam));
            }
            saveObjectToList(taskId, buzTaskQuestions);
        }
        */

        buzTaskQuestions = buzTaskQuestionMapper.selectBuzTaskQuestionList(questionParam);
        for (BuzTaskQuestion question : buzTaskQuestions) {
            BuzTaskOption optionParam = new BuzTaskOption();
            optionParam.setBuzTaskQuestionId(question.getId());
            optionParam.setBuzTaskId(buzTask.getId());
            question.setBuzTaskOptions(buzTaskOptionMapper.selectBuzTaskOptionList(optionParam));
        }
        saveObjectToList(taskId, buzTaskQuestions);

        //如果getExamType为0则随机选题
        if(buzTask.getExamType() == 0){
            Collections.shuffle(buzTaskQuestions);
            buzTaskQuestions = buzTaskQuestions.stream().limit(buzTask.getExamQuestions()).collect(Collectors.toList());
        }        
        
        List<BuzTaskUserOption> userOptionList=new ArrayList();
        
        
        BuzTaskOption optionParamQuery = new BuzTaskOption();        
        optionParamQuery.setBuzTaskId(buzTask.getId());
        List<BuzTaskOption> optionList=buzTaskOptionMapper.selectBuzTaskOptionList(optionParamQuery);
        
        for (BuzTaskQuestion question : buzTaskQuestions) {
        	/*
        	BuzTaskUserQuestion userQuestion=new BuzTaskUserQuestion();
        	userQuestion.setAksImg(question.getAksImg());
        	userQuestion.setAsk(question.getAsk());
        	userQuestion.setBuzTaskId(question.getBuzTaskId());
        	userQuestion.setBuzTaskUserId(taskUser.getId());
        	userQuestion.setQuestionMemo(question.getQuestionMemo());
        	userQuestion.setQuestionType(question.getQuestionType());
        	userQuestion.setRemark(question.getRemark());
        	userQuestion.setAnswerKey(question.getAnswerKey());
        	userQuestion.setId(generateGuid());
        	buzTaskUserQuestionMapper.insertBuzTaskUserQuestion(userQuestion);
        	*/
        	
        	List<BuzTaskOption> optionAddList=new ArrayList();
        	for(int j=0;j<optionList.size();j++) {
        		BuzTaskOption optionParam =optionList.get(j);
        		if(question.getId().equals(optionParam.getBuzTaskQuestionId())) {
        			optionAddList.add(optionParam);;
        		}
        	}
        	/*
            BuzTaskOption optionParam = new BuzTaskOption();
            optionParam.setBuzTaskQuestionId(question.getId());
            optionParam.setBuzTaskId(buzTask.getId());
            List<BuzTaskOption> optionList=buzTaskOptionMapper.selectBuzTaskOptionList(optionParam);
            */
            question.setBuzTaskOptions(optionAddList);
            /*
            for(int j=0;j<optionList.size();j++) {
            	BuzTaskUserOption userOption=new BuzTaskUserOption();
            	userOption.setBuzTaskId(taskId);
            	userOption.setBuzTaskUserId(taskUserId);
            	if(userOption.getId()==null) {
            		userOption.setId(UUID.randomUUID().toString().replace("-", ""));
                }
            	
            	userOptionList.add(userOption);
            }
            */
        }
        
        //buzTaskUserOptionMapper.batchInsertBuzTaskUserOption(userOptionList);

        addData.setBuzTask(buzTask);
        addData.setBuzTaskUser(taskUser);
        addData.setBuzTaskQuestions(buzTaskQuestions);
        return addData;
    }

    private String generateGuid(){
        return UUID.randomUUID().toString().replace("-","");
    }
    private String saveOrUpdateBuzTask(BuzTask buzTask){
        if(StringUtils.isBlank(buzTask.getId())) {
            buzTask.setId(generateGuid());
            buzTaskMapper.insertBuzTask(buzTask);
        }else {
            buzTaskMapper.updateBuzTask(buzTask);
        }
        return buzTask.getId();
    }

    public int saveOrUpdateMember(BuzMember buzMember){
    	
    	System.out.println("-------------开始保存用户电话号码和地区："+buzMember.getOpenId());
    	BuzMember member=new BuzMember();
    	member.setOpenId(buzMember.getOpenId());
    	List<BuzMember> memberList=buzMemberService.selectBuzMemberList(member);
    	
    	
    	
    	if(memberList!=null&&memberList.size()>0) {
    		member=memberList.get(0);
    		member.setAddress(buzMember.getAddress());
    		member.setArea(buzMember.getArea());
    		member.setAvatar(buzMember.getAvatar());
    		member.setMemberName(buzMember.getMemberName());
    		member.setPhone(buzMember.getPhone());
    		
    		return buzMemberMapper.updateBuzMember(member);
    	}else {
    		buzMember.setId(buzMember.getOpenId());
    		return buzMemberMapper.insertBuzMember(buzMember);
    	}
    	
        
    }

    private String saveOrUpdateBuzTaskQuestion(BuzTaskQuestion buzTaskQuestion){
    	/*
        if(StringUtils.isBlank(buzTaskQuestion.getId())) {
            buzTaskQuestion.setId(generateGuid());
            buzTaskQuestionMapper.insertBuzTaskQuestion(buzTaskQuestion);
        }else {
            buzTaskQuestionMapper.updateBuzTaskQuestion(buzTaskQuestion);
        }
        */
    	buzTaskQuestion.setId(generateGuid());
        buzTaskQuestionMapper.insertBuzTaskQuestion(buzTaskQuestion);
        return buzTaskQuestion.getId();
    }

    private String saveOrUpdateBuzTaskOption(BuzTaskOption buzTaskOption){
    	/*
        if(StringUtils.isBlank(buzTaskOption.getId())) {
            buzTaskOption.setId(generateGuid());
            buzTaskOptionMapper.insertBuzTaskOption(buzTaskOption);
        }else {
            buzTaskOptionMapper.updateBuzTaskOption(buzTaskOption);
        }
        */
    	buzTaskOption.setId(generateGuid());
        buzTaskOptionMapper.insertBuzTaskOption(buzTaskOption);
        return buzTaskOption.getId();
    }

    private String saveOrUpdateBuzTaskAwards(BuzTaskAwards buzTaskAwards){
        if(StringUtils.isBlank(buzTaskAwards.getId())){
            buzTaskAwards.setId(generateGuid());
            buzTaskAwardsMapper.insertBuzTaskAwards(buzTaskAwards);
        }else{
            buzTaskAwardsMapper.updateBuzTaskAwards(buzTaskAwards);
        }
        return buzTaskAwards.getId();
    }

    private String saveOrUpdateBuzTaskUser(BuzTaskUser taskUser){
        if(StringUtils.isBlank(taskUser.getId())){
            taskUser.setId(generateGuid());
            System.out.println("--------------新增答题活动---------------");
            buzTaskUserMapper.insertBuzTaskUser(taskUser);
        }else{
        	System.out.println("--------------更新答题活动---------------");
            buzTaskUserMapper.updateBuzTaskUser(taskUser);
        }
        return taskUser.getId();
    }
    private String saveOrUpdateBuzTaskArea(BuzTaskArea buzTaskArea){
        if(StringUtils.isBlank(buzTaskArea.getId())){
            buzTaskArea.setId(generateGuid());
            buzTaskAreaMapper.insertBuzTaskArea(buzTaskArea);
        }else{
            buzTaskAreaMapper.updateBuzTaskArea(buzTaskArea);
        }
        return buzTaskArea.getId();
    }
    @Transactional
    public BuzTaskUser getUserTaskAwards(UserTaskAddData addData) throws Exception{
    	
    	// 获取答题情况信息
    	BuzTaskUser buzTaskUser =  buzTaskUserMapper.selectBuzTaskUserById(addData.getTaskUserId());
        //BuzTaskUser buzTaskUser = new BuzTaskUser();
        //buzTaskUser.setTaskId(addData.getTaskId());
        //buzTaskUser.setMemberId(addData.getMemberId());
        //buzTaskUser = buzTaskUserMapper.selectBuzTaskUser(buzTaskUser);
    	if(buzTaskUser==null) {
    		return new BuzTaskUser();
    	}

        BuzTask task = buzTaskMapper.selectBuzTaskById(addData.getTaskId());
        List<BuzTaskAwards> taskAwards = buzTaskAwardsMapper.selectBuzTaskAwardsListByTaskId(addData.getTaskId());

        //待完成
        int time_diff = Math.abs((int) (task.getEndTime().getTime() - DateUtils.getNowDate().getTime()));
        int total_award_nums = taskAwards.stream().mapToInt(BuzTaskAwards::getAwardNums).sum();

        
        //int remian_award_nums = total_award_nums - buzTaskUserMapper.getCountByTaskId(addData.getTaskId());

        // fly 20231110 个人抽奖次数应为taskid与memberid 以及can_awards_flage为1的集合
        int remian_award_nums = total_award_nums - buzTaskUserMapper.getAwardTimesByTaskIdAndMemberId(buzTaskUser);
        
        //总剩余次数小于0则返回未中奖
        if(remian_award_nums <= 0){
            return buzTaskUser;
        }
        
        //根据 awardNumsMinu 字段，多少分钟发一个奖品，来计算最近X分钟，是否已经发过奖品，如果有，则不中奖
        /*2024-05-31,要求去除该限制，2024-06-06要求恢复该限制，改成1分钟1个奖*/
        /*
        if(task.getAwardNumsMinu()!=null) {
        	int awardNumsMinu=buzTaskUserMapper.getAwardCountByPerMinu(task.getAwardNumsMinu());
        	if(awardNumsMinu>=3) {
        		return buzTaskUser;
        	}
        }
        */
        
        /****按时间平均分配奖项的逻辑
        
        //每天剩余次数小于0则返回未中奖
        int remain_award_nums_perday = remian_award_nums/((time_diff/1000/60/60/24)<1?1:(time_diff/1000/60/60/24)) - buzTaskUserMapper.getCountByTaskIdByCurrDay(addData.getTaskId());
        if(remain_award_nums_perday <= 0){
            return buzTaskUser;
        }
        //每小时剩余次数小于0则返回未中奖
        int remian_award_nums_hours = (remain_award_nums_perday<24 ? 1 : remian_award_nums/(time_diff/1000/60/60)) - buzTaskUserMapper.getCountByTaskIdByCurrHour(addData.getTaskId());
        if(remian_award_nums_hours <= 0){
            return buzTaskUser;
        }
        */
        //计算是否在抽奖时间段内
        if(StringUtils.isNoneBlank(task.getAwardsTimeInterval())) {
            boolean timeFlag = false;
            String[] timeIntervals = task.getAwardsTimeInterval().split(",");
            for (String timeInterval : timeIntervals) {
                String[] timesArray = timeInterval.split("-");
                String begin = timesArray[0];
                String end = timesArray[1];

                Date date = new Date();
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                    Calendar dateNow = Calendar.getInstance();
                    dateNow.setTime(date);

                    Date b = df.parse(DateUtils.dateTimeNow("yyyy-MM-dd") + " " + begin + ":00");
                    Date e = df.parse(DateUtils.dateTimeNow("yyyy-MM-dd") + " " + end + ":00");

                    Calendar beginDate = Calendar.getInstance();
                    beginDate.setTime(b);
                    Calendar endDate = Calendar.getInstance();
                    endDate.setTime(e);

                    if (dateNow.after(beginDate) && dateNow.before(endDate)) {
                        timeFlag = true;
                        break;
                    }
                } catch (Exception e) {
                    System.out.println(timeInterval);
                    e.printStackTrace();
                }
            }
            //如果不在抽奖时间段内，则返回空对象
            if (!timeFlag) {
                return buzTaskUser;
            }
        }


        //根据中奖率
        int rate = 10; //中奖率
        
        String awardsRate= task.getAwardsRate();
        if(awardsRate!=null&&!awardsRate.equals("")) {
        	if(awardsRate.indexOf(".")>0) awardsRate=awardsRate.substring(0, awardsRate.indexOf("."));
        	rate =new Integer(awardsRate);
        }
        
        //如果不能中奖，则设置中奖概率为0
        if(!addData.isAwardFlag()) {
        	rate=0;
        }
        
        //总中奖概率计算
        /********
         * 从0-99数中随机生成一个数，如果这个数小于rate，则中奖。
         * 例如中奖率30%，随机生成的数小于30，则中奖
         */
        Random random = new Random();
        //如果0到N的随机数等于N的中值，则中奖
        int randomNum = random.nextInt(100);
        if(randomNum<rate){//中奖
            //对奖项随机排序取第一个
            List<BuzTaskAwardsJackpot> jackpots = buzTaskAwardsJackpotMapper.selectBuzTaskAwardsJackpotListByTaskId(addData.getTaskId());

            Collections.shuffle(jackpots);
            if(!jackpots.isEmpty()) {
                BuzTaskAwardsJackpot buzTaskAwardsJackpot = jackpots.get(0);
                BuzTaskAwards buzTaskAwards = buzTaskAwardsMapper.selectBuzTaskAwardsById(buzTaskAwardsJackpot.getBuzTaskAwardsId());

                if(buzTaskAwards!=null) {
                	
                	Date awardsDate = DateUtils.getNowDate();
                	Date awardsTimeEnd=DateUtil.offsetMinute(awardsDate, 5);
                //如果奖项还有剩余
                //if ((buzTaskAwards.getLeftAwardNums() == null ? 0 : buzTaskAwards.getLeftAwardNums()) > 0) {
                	try {
	                    //更新奖池	                    
	                    buzTaskAwardsJackpot.setBuzTaskUserId(buzTaskUser.getId());
	                    buzTaskAwardsJackpot.setAwardTime(awardsDate);
	                    buzTaskAwardsJackpotMapper.updateBuzTaskAwardsJackpot(buzTaskAwardsJackpot);
                	}catch(Exception e) {
                		throw new Exception("系统异常");
                	}

                    //确认中奖后更新
                    List<BuzTaskAwardsJackpot> buzTaskAwardsJackpotByIdAndUser = buzTaskAwardsJackpotMapper.selectBuzTaskAwardsJackpotByIdAndUser(buzTaskAwardsJackpot);
                    if (!buzTaskAwardsJackpotByIdAndUser.isEmpty()) {
                        //如果是随机金额
                        if(buzTaskAwards.getAwardType() == 1){
                            double awardsMoney = random() * (buzTaskAwards.getMaxMoney() - buzTaskAwards.getMinMoney() + 1);
                            buzTaskUser.setAwardsMoney(awardsMoney);
                        }else{
                            buzTaskUser.setAwardsMoney(buzTaskAwards.getSingleAvgMoney().doubleValue());
                        }

                        //String url = gethbTicketUrl(buzTaskUser.getId(),buzTaskUser.getAwardsMoney().toString());
                        //改成直发红包
                        //String url = sendRedPackUrl(buzTaskUser.getId(), buzTaskUser.getMemberId(), buzTaskUser.getAwardsMoney().toString());

                        //buzTaskUser.setAwardsUrl(url);
                        buzTaskUser.setAwardsLevel(buzTaskAwards.getAwardsLevel());
                        buzTaskUser.setAwardName(buzTaskAwards.getAwardName());
                        buzTaskUser.setAwardsTime(awardsDate);
                        buzTaskUser.setReceiveAwardsTime(null);
                        buzTaskUser.setAwardsTimeEnd(awardsTimeEnd);
                        // buzTaskUserMapper.insertBuzTaskUser(buzTaskUser);
                        //先保存领奖链接
                        buzTaskUserMapper.updateBuzTaskUser(buzTaskUser);
                        //不知道为什么，会有领奖时间。把领奖时间置空
                        //buzTaskUserMapper.nullReceiveAwardsTime(buzTaskUser);

                        buzTaskAwards.setLeftAwardNums(buzTaskAwards.getLeftAwardNums() - 1);
                        buzTaskAwardsMapper.updateBuzTaskAwards(buzTaskAwards);
                        //返回中奖信息时不带领奖链接
                        //buzTaskUser.setAwardsUrl("");
                        return buzTaskUser;
                    }
                //}
                }else {
                	//没有剩余奖项了，不能中奖
                	Date awardsDate = DateUtils.getNowDate();
                	buzTaskUser.setAwardsTime(awardsDate);
                	buzTaskUser.setReceiveAwardsTime(null);
                	buzTaskUserMapper.updateBuzTaskUser(buzTaskUser);
                }
            }else {
            	//没有剩余奖项了，不能中奖
            	Date awardsDate = DateUtils.getNowDate();
            	buzTaskUser.setAwardsTime(awardsDate);
            	buzTaskUser.setReceiveAwardsTime(null);
            	buzTaskUserMapper.updateBuzTaskUser(buzTaskUser);
            }
        }else {//没有中奖
        	Date awardsDate = DateUtils.getNowDate();
        	buzTaskUser.setAwardsTime(awardsDate);
        	buzTaskUser.setReceiveAwardsTime(null);
        	buzTaskUserMapper.updateBuzTaskUser(buzTaskUser);
        }
        
      //不知道为什么，会有领奖时间。把领奖时间置空
        //buzTaskUserMapper.nullReceiveAwardsTime(buzTaskUser);

        return buzTaskUser;
    }

	@Override
	public boolean publishTask(String taskId) {
		// 发布需要做时间判断
		int res= buzTaskMapper.publishTask(taskId,2);

        //发布活动生成活动奖池
//        List<BuzTaskAwards> buzTaskAwardsList = buzTaskAwardsMapper.selectBuzTaskAwardsListByTaskId(taskId);
//        for (BuzTaskAwards buzTaskAwards : buzTaskAwardsList) {
//            for(int i=0; i<buzTaskAwards.getAwardNums(); i++) {
//                BuzTaskAwardsJackpot buzTaskAwardsJackpot = new BuzTaskAwardsJackpot();
//                buzTaskAwardsJackpot.setId(generateGuid());
//                buzTaskAwardsJackpot.setBuzTaskId(taskId);
//                buzTaskAwardsJackpot.setBuzTaskAwardsId(buzTaskAwards.getId());
//                buzTaskAwardsJackpot.setAwardName(buzTaskAwards.getAwardName());
//                buzTaskAwardsJackpot.setAwardsLevel(buzTaskAwards.getAwardsLevel());
//                buzTaskAwardsJackpotMapper.insertBuzTaskAwardsJackpot(buzTaskAwardsJackpot);
//            }
//        }
		return res==1;
	}

    /**
    * 访问第三方接口生成红包链接
    */
    private String gethbTicketUrl(String orderid, String money){
        String uid = "10810602";
        String type = "0";
        long reqtick= new Date().getTime();
        reqtick=reqtick/1000;
        //System.out.println("----------时间戳："+reqtick);
        //String reqtick = "1515133732";
        String apikey = "TSGCY6rzFW6TzhAd";
        System.out.println("----------money："+money);
        float fen=new Float(money)*100;
        System.out.println("----------fen："+fen);
        //超时参数 默认3天
        String expire = "259200";
        //sign = md5(uid+type+orderid+money+reqtick+apikey)
        String sign = Md5Utils.hash(uid+type+orderid+fen+reqtick+apikey).toLowerCase();
        String url = "https://www.yaoyaola.net/exapi/hbticket?uid="+uid+"&type="+type+"&orderid="+orderid+"&money="+fen+"&reqtick="+reqtick+"&sign="+sign+"&expire="+expire;
        String result = "https://www.yaoyaola.net/exapi/gethb/"+uid;

        String responseStr = restTemplate.getForObject(url, String.class);
        System.out.println("--------------------------红包接口返回内容-----------"+responseStr);
        JSONObject jsonObject = JSONObject.parseObject(responseStr);
        if (jsonObject != null && jsonObject.containsKey("ticket")) {
            String ticket = jsonObject.getString("ticket");
            result = result+"?ticket="+ticket;
        }
        return result;
    }


    /**
     * 第三方红包直发接口
     */
    private String sendRedPackUrl(String orderId, String openId, String money){
        String uid = "10810602";
        String type = "0";
        long reqtick= new Date().getTime();
        reqtick=reqtick/1000;

        String apikey = "TSGCY6rzFW6TzhAd";
        System.out.println("----------money："+money);
        float fen=new Float(money)*100;
        System.out.println("----------fen："+fen);

        //sign = md5(uid+type+orderid+money+reqtick+openId+apikey)
        String sign = Md5Utils.hash(uid+type+orderId+fen+reqtick+openId+apikey).toLowerCase();
        String url = "https://www.yaoyaola.net/exapi/SendRedPackToOpenid?uid="+uid+"&type="+type+"&orderid="+orderId+"&money="+fen+"&reqtick="+reqtick+"&openid="+openId+"&sign="+sign;

        String responseStr = restTemplate.getForObject(url, String.class);
        System.out.println("--------------------------红包接口返回内容-----------"+responseStr);
        JSONObject jsonObject = JSONObject.parseObject(responseStr);
        if (jsonObject != null && jsonObject.containsKey("ticket")) {
            String ticket = jsonObject.getString("ticket");
        }
        return url;
    }

    public String getAnswerByQuestionId(String id){
        BuzTaskQuestion question = buzTaskQuestionMapper.selectBuzTaskQuestionById(id);
        if(question != null) {
            return question.getAnswerKey();
        }else {
            return "";
        }
    }
}
